package org.jeecg.modules.quartz.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.QiWeiUtil;
import org.jeecg.modules.qiwei.shenpi.QingJiaShenPi;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @Description:  企业微信 同步定时任务
 *
 * 此处的同步是指 当定时任务的执行时间大于任务的时间间隔时
 * 会等待第一个任务执行完成才会走第二个任务
 *
 *
 * @author: taoyan
 * @date: 2020年06月19日
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class QiWeiAsyncJob implements Job {

    @Autowired
    private QiWeiUtil qiWeiUtil;

    @Autowired
    private ApplicationContext applicationContext;
    private String accessToken;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(" --- 企业微信同步任务调度开始 --- ");

        String beginTime = "";
        String endTime = "";
        try {
            beginTime = DateUtils.str2Time("2024-11-01 00:00:00");
            endTime = DateUtils.str2Time("2024-11-30 23:59:59");

            log.info("beginTime:"+beginTime);
            log.info("endTime:"+endTime);

//            while(true){
                List<String> approvalData = qiWeiUtil.getApprovalData(beginTime, endTime, 0, 5, null);

                //1. 根据单号得到详情
                approvalData.forEach(billNo->{
                    log.info("单号："+billNo);
                    JSONObject approvalDetail = qiWeiUtil.getApprovalDetail(billNo);
                    log.info("审批详情："+approvalDetail);
                    //2. 处理审批详情
                    handleApprovalDetail(approvalDetail);
                });

//                if ((long) approvalData.size() <100){
//                    break;
//                }
//            }

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }


        //测试发现 每5秒执行一次
        log.info(" --- 企业微信同步任务执行完毕，时间："+DateUtils.now()+"---");
    }

    private void handleApprovalDetail(JSONObject approvalDetail) {
        Integer errcode = approvalDetail.getInteger("errcode");
        if (errcode !=0){
            throw new RuntimeException("获取审批详情失败："+approvalDetail.getString("errmsg"));
        }

        JSONObject info = approvalDetail.getJSONObject("info");
        //String spNo = info.getString("sp_no"); //审批单号
        String spName = info.getString("sp_name"); //审批名称

        if("请假".equals(spName)){
            QingJiaShenPi qingJiaShenPi =(QingJiaShenPi) applicationContext.getBean("qingJiaShenPi");
            qingJiaShenPi.handleApprovalDetail(approvalDetail);
        }


    }




}
